import React, { useEffect, useState } from 'react';
import { Modal, ScrollView, StyleSheet, TouchableOpacity, Image, Button } from 'react-native';
import { Box, Input, Text, View, Image as NImage, Badge } from 'native-base';
import { CommonStyle } from '../common/commonStyle.ts';
import HomeRequest from '../request/homeRequest.ts';
import { Loading } from '../component/LoadingOverlay.tsx';
import { EOrderPayState, EOrderState, EOrderAppointState } from '../common/enum.ts';
import { navigate } from '../common/navigationService.ts';
import Tools from '../utils/Tools.ts';

interface IOrderCardProps {
  orderInfo?: IOrderList;
  index: number;
  onContinuePay?: () => void; //继续支付
  onRescueProgress?: () => void; //救援进度
  onCloseAlarm?: () => void; //解除警报
  onCallPhone?: () => void; //联系商家
  onEvaluate?: () => void; //评价
  onRepeatPlaceOrder?: () => void; //再来一单
}

const OrderCard: React.FC<IOrderCardProps> = ({ orderInfo, onContinuePay, onRescueProgress, onCloseAlarm, onCallPhone, onEvaluate, onRepeatPlaceOrder, index }) => {
  const badgeStateShow = (state: IOrderList, type: string) => {
    let stateStyle = '';
    switch (type === 'appoint' ? state.appointmentState : state.payState) {
      case 1:
        stateStyle = 'coolGray';
        break;
      case 4 | 3 | 7:
        stateStyle = 'error';
        break;
      case 5:
        stateStyle = 'success';
        break;
      case 10:
        stateStyle = 'warning';
        break;
      case 15:
        stateStyle = 'warning';
        break;
      default:
        stateStyle = 'coolGray';
        break;
    }
    if (type === 'appoint') {
      if (state.appointmentState) {
        return <Badge colorScheme={stateStyle}>{EOrderAppointState[state.appointmentState]}</Badge>;
      }
    } else {
      if (state.orderState !== 15) {
        return (
          <Badge ml={4} colorScheme={stateStyle}>
            {EOrderPayState[state.payState]}
          </Badge>
        );
      } else {
        return '';
      }
    }
  };

  const btnShow = (item: IOrderList) => {
    const buttons = [];

    // 根据不同条件添加按钮到数组
    if (item.orderType === 8 && item.orderState < 15) {
      buttons.push({
        text: '解除警报',
        color: '#ff3141',
        type: 'alarm',
      });
    }
    
    if (item.orderType === 11 && item.orderState < 15) {
      buttons.push({
        text: '救援进度',
        color: '#ff8f1f',
        type: 'rescue',
      });
    }
    
    if (item.orderState === 20 && !item.evaluateState) {
      buttons.push({
        text: '评价',
        color: '#ccc',
        type: 'evaluate',
      });
    }
    
    if (item.orderState !== 20 && item.evaluateState && item.orderType !== 11) {
      buttons.push({
        text: '联系商家',
        color: '#ccc',
        type: 'phone',
      });
    }
    
    if ((item.payState === 1 || item.payState === 4) && item.orderState < 15) {
      buttons.push({
        text: '继续支付',
        color: CommonStyle.mainColor,
        type: 'pay',
      });
    } else if (item.payType !== 5) {
      buttons.push({
        text: '再来一单',
        color: CommonStyle.mainColor,
        type: 'repeat',
      });
    }
    
    // 渲染按钮
    return (
      <View style={{flexDirection:'row',flexWrap:'wrap'}}>
        {buttons.map((button, index) => (
          <TouchableOpacity
            key={index}
            onPress={() => {
              handleOrderOperator(button.type, item);
            }}
            style={{ backgroundColor: button.color,marginLeft:6, paddingHorizontal: 10, paddingVertical: 5, borderRadius: 8, marginBottom: 5 }}
          >
            <Text style={{ color: '#fff', fontWeight: 'bold' }}>{button.text}</Text>
          </TouchableOpacity>
        ))}
      </View>
    );
  };

  const handleOrderOperator = (type: string, item: IOrderList) => {
    switch (type) {
      case 'alarm':
        break;
      case 'rescue':
        navigate('rescueProgress', { orderId: item.orderId });
        break;
      case 'evaluate':
        navigate('orderEvaluate', { orderId: item.orderId });
        break;
      case 'phone':
        Tools.callPhone(item.businessPhone);
        break;
      case 'pay':
        break;
      case 'repeat':
        break;
    }
  };

  return (
    <View style={styles.container} key={index}>
      <View style={styles.title}>
        <View style={styles.titleLeft}>
          <Image
            source={{
              uri: orderInfo?.businessLogo,
            }}
            alt=""
            width={60}
            height={60}
            borderRadius={8}
          />
          <Text style={{ marginLeft: 10 }}>{orderInfo!.businessName}</Text>
        </View>
        <View style={styles.titleRight}>
          <Text style={{ marginBottom: 4 }}>{orderInfo?.errorState === 3 ? '取消申请中' : orderInfo?.orderState !== undefined ? EOrderState[orderInfo.orderState] : '未知状态'}</Text>
          <View style={{ flexDirection: 'row' }}>
            {badgeStateShow(orderInfo!, 'pay')}
            {badgeStateShow(orderInfo!, 'appoint')}
          </View>
        </View>
      </View>
      {orderInfo?.goodsList.map((cItem, cIndex) => (
        <View style={styles.info} key={cIndex}>
          <View style={styles.infoLeft}>
            <NImage
              source={{
                uri: cItem.images,
              }}
              alt=""
              size={20}
              borderRadius={8}
            />
            <Text style={{ textAlign: 'center' }}>{cItem.name}</Text>
          </View>
          <View style={styles.infoRight}>
            <Text style={{ fontWeight: 'bold', fontSize: 16 }}>￥{orderInfo.realAmount}</Text>
            <Text>共 {orderInfo.goodsList.length} 件</Text>
          </View>
        </View>
      ))}
      <View style={styles.operator}>
        <View style={styles.operatorLeft}>
          <Text>呼叫器：{orderInfo!.beeperName}</Text>
          <Text>日期：{orderInfo!.createDate}</Text>
        </View>
        <View style={styles.operatorRight}>{btnShow(orderInfo!)}</View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
    marginBottom: 10,
  },
  title: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginBottom: 14,
  },
  titleLeft: {
    flex: 1,
    flexDirection: 'row',
  },
  titleRight: {
    flex: 0,
    alignItems: 'flex-end',
  },
  info: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 14,
  },
  infoLeft: {
    flex: 0,
  },
  infoRight: {
    flex: 1,
    alignItems: 'flex-end',
  },
  operator: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  operatorLeft: {
    flex: 1,
  },
  operatorRight: {
    flex: 0,
  },
});

export default OrderCard;
